﻿using System;
using System.IO;
using System.Reflection;
using Sharp.Infrastructure;

namespace Sharp.Platform.Configuration
{
    /// <summary>
    /// 系统级配置管理
    /// </summary>
    public class SystemConfigManage
    {

        #region 读取配置
        /// <summary>
        /// 读取配置
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T Read<T>() where T : class, ISystemConfig, new()
        {
            T t = new T();
            t = SerializableHelper.DeSerialize<T>(new FileInfo(WebServer.MapPath("~/App_Data/" + t.ConfigFileName)));
            if (t == null)
            {
                return new T();
            }
            return t;
        }
        /// <summary>
        /// 读取配置
        /// </summary>
        /// <param name="configType"></param>
        /// <returns></returns>
        public static ISystemConfig Read(Type configType)
        {
            ISystemConfig configInstance = configType.Assembly.CreateInstance(configType.FullName) as ISystemConfig;

            FileInfo fi = new FileInfo(WebServer.MapPath(string.Format("~/App_Data/{0}", configInstance.ConfigFileName)));

            var systemconfig = SerializableHelper.DeSerialize(fi, configType) as ISystemConfig;
            //如果没有配置那么就用默认值
            if (systemconfig == null)
            {
                systemconfig = configInstance;
            }
            return systemconfig;
        }
        #endregion

        /// <summary>
        /// 保存配置
        /// </summary> 
        /// <param name="config"></param>
        public static void Save(ISystemConfig config)
        {
            string filepath = WebServer.MapPath(string.Format("~/App_Data/{0}", config.ConfigFileName));

            SerializableHelper.Serialize(config, filepath);

            Clear(config);
        }

        private static void Clear(ISystemConfig config)
        {

        }

        /// <summary>
        /// 设置值
        /// </summary>
        /// <param name="cfg"></param>
        /// <param name="propertyName"></param>
        /// <param name="value"></param>
        /// <remarks>顺便保存了配置文件</remarks>
        public static object SetValue(Type cfg, string propertyName, string value)
        {
            var config = Read(cfg);
            PropertyInfo pi = config.GetType().GetProperty(propertyName);
            if (pi != null)
            {
                try
                {
                    return ChangeType(value, pi.PropertyType);
                }
                catch
                {
                    return null;
                }
            }
            return null;
        }

        static object ChangeType(object value, Type type)
        {
            if (value == null && type.IsGenericType)
                return Activator.CreateInstance(type);
            if (type == typeof(Guid))
                return new Guid(value as string);

            if (type == typeof (bool))
            {
                if (value.ToString() == "on")
                {
                    value = "true";
                }
                return Convert.ToBoolean(value);
            }

            if (value == null)
                return null;
            if (type == value.GetType())
                return value;
            if (type.IsEnum)
            {
                if (value is string)
                    return Enum.Parse(type, value as string);
                else
                    return Enum.ToObject(type, value);
            }
            if (!type.IsInterface && type.IsGenericType)
            {
                Type innerType = type.GetGenericArguments()[0];
                object innerValue = ChangeType(value, innerType);
                return Activator.CreateInstance(type, new object[] { innerValue });
            }

            if (!(value is IConvertible)) return value;
            return Convert.ChangeType(value, type);
        }
    }
}